import 'dart:io';
import 'dart:math';
import 'dart:ui' as ui;

import 'package:animations/animations.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:photo_view/photo_view.dart';
import 'package:wanandroid_flutter/asperct_raio_image.dart';

import '../r.dart';

class WindowHomePage extends StatefulWidget {
  @override
  _WindowHomePageState createState() => _WindowHomePageState();
}

class _WindowHomePageState extends State<WindowHomePage> {
  TextEditingController _textEditingController;
  List<String> _images = [];
  List<Map<String, dynamic>> _image = [];
  List<int> _ran = [];
  List<int> _ranF = [];
  Dio _dio;

  @override
  void initState() {
    _textEditingController = TextEditingController();
    _dio = Dio();
    super.initState();
  }

  _randomBit(int len) {
    String scopeF = '123456789'; //首位
    String scopeC = '0123456789'; //中间
    String result = '';
    for (int i = 0; i < len; i++) {
      if (i == 0) {
        result = scopeF[Random().nextInt(scopeF.length)];
      } else {
        result = result + scopeC[Random().nextInt(scopeC.length)];
      }
    }
    return result;
  }

  dynamic _imageData;

  @override
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.clear),
        onPressed: () {
          for (var i = 0; i < 100; i++) {
            var randomBit = _randomBit(5);
            if (_ran.contains(randomBit) || _ranF.contains(randomBit)) {
              continue;
            }
            var url = 'http://img.500px.me/500px10244$randomBit.jpg!p5';
            _dio.get(url).then((value) {
              if (value.statusCode == HttpStatus.ok) {
                _images.add(url);
                _image.add({'url': url, 'data': value.data});
                _ran.add(randomBit);
              } else {
                _ranF.add(randomBit);
              }
            });
          }
          setState(() {
            // _images.clear();
          });
        },
      ),
      body: Container(
        height: double.infinity,
        width: double.infinity,
        padding: const EdgeInsets.only(top: 8.0, left: 8.0, right: 8.0),
        decoration: BoxDecoration(
            image: DecorationImage(
                image: ExactAssetImage(
                  R.assetsImagesBg,
                ),
                fit: BoxFit.fitWidth)),
        child: Column(
          mainAxisAlignment: _images.isEmpty
              ? MainAxisAlignment.center
              : MainAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            ClipRRect(
              borderRadius: BorderRadius.all(Radius.circular(60)),
              child: Container(
                // padding: EdgeInsets.symmetric(horizontal: 50),
                width: size.width - 100 * 2,
                color: Colors.white,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Expanded(
                        child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: TextField(
                        controller: _textEditingController,
                        decoration:
                            InputDecoration.collapsed(hintText: '需要解析的网址'),
                      ),
                    )),
                    FlatButton(
                      onPressed: _parseURL,
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text(
                          '开始解析',
                          style: TextStyle(),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            _images.isEmpty
                ? SizedBox()
                : Flexible(
                    fit: FlexFit.loose,
                    child: Padding(
                      padding: const EdgeInsets.fromLTRB(8.0, 8.0, 8.0, 0.0),
                      child: SingleChildScrollView(
                        child: Wrap(
                          children: _images
                              .map((e) => AsperctRaioImage.network(e,
                                  builder: _imageWidget))
                              .toList(),
                        ),
                      ),
                    ),
                  )
          ],
        ),
      ),
    );
  }

  void _parseURL() {
    var text = _textEditingController.text;
    if (!text.contains('https://500px.com.cn/')) {
      showDialog(
          context: context,
          child: AlertDialog(
            title: Text('错误的解析'),
            content: Text('暂不支持该网址解析,请联系作者进行有偿开发！！！'),
            actions: [
              FlatButton(
                onPressed: () => Navigator.pop(context),
                child: Text('确定'),
              )
            ],
          ));
      return;
    }
    for (var i = 1; i <= 6; i++) {
      var url =
          'http://img.500px.me${text.substring(text.lastIndexOf('/'))}.jpg!p$i';
      _images.add(url);
    }
    setState(() {});
  }

  Widget _imageWidget(
      BuildContext context, AsyncSnapshot<ui.Image> snapshot, String url) {
    Widget widget;
    if (snapshot.hasError) {
      setState(() {
        _images.remove(url);
      });
      return SizedBox();
      widget = Text('${snapshot.error.toString()}');
    } else {
      widget = GestureDetector(
        onTap: () {
          showDialog(
              context: context,
              child: Dialog(
                backgroundColor: Colors.transparent,
                child: Image.network(url),
              ));
        },
        onSecondaryTap: () async {
          showDialog(
              context: context,
              child: AlertDialog(
                title: Text("复制图片地址"),
                content: Text('快点下班！！！'),
                actions: [
                  RaisedButton(
                    color: Colors.blueAccent,
                    onPressed: () async {
                      var image = snapshot.data;
                      var file = File(
                          '${url.split('/').last.split('.').first}-${image.width.toInt()}-${image.height.toInt()}.jpg');
                      print(file.absolute);

                      // var clipboardData = ClipboardData(text: url);
                      // Clipboard.setData(clipboardData);
                      // print('复制成功： ${clipboardData.text}');

                      Dio()
                          .download(url, file.absolute.path,
                              options: Options(
                                method: 'GET',
                                contentType: 'image/jpeg',
                                followRedirects: true,
                                responseType: ResponseType.bytes,
                                validateStatus: (status) {
                                  return status < 500;
                                },
                              ))
                          .catchError((error) {
                        Scaffold.of(context).showSnackBar(SnackBar(
                          content: Text('下载失败:${error.toString()}'),
                        ));
                      }).whenComplete(() {
                        print('下载完成');
                        Scaffold.of(context).showSnackBar(SnackBar(
                          content: Text('下载完成'),
                        ));
                        Navigator.pop(context);
                      });

                      // if (!file.existsSync()) {
                      // image?.toByteData()?.then((value) {
                      //   print('文件有数据');
                      //   file.create().then((f) {
                      //     var sink = f.openWrite();
                      //     sink.write(value);
                      //     sink.flush();
                      //     sink.close();
                      //   });
                      // });
                      // } else {}
                    },
                    child: Text('复制地址'),
                  ),
                  FlatButton(
                    onPressed: () => Navigator.pop(context),
                    child: Text('取消'),
                  ),
                ],
              ));
        },
        child: Stack(
          children: [
            Image.network(
              url,
              fit: BoxFit.contain,
              loadingBuilder: (BuildContext context, Widget child,
                  ImageChunkEvent loadingProgress) {
                if (loadingProgress == null)
                  return ConstrainedBox(
                      constraints: BoxConstraints(
                          maxHeight: 1080 / 3,
                          maxWidth: 1920 / 3,
                          minHeight: 200,
                          minWidth: 100),
                      child: child);
                return Center(
                  child: CircularProgressIndicator(
                    value: loadingProgress.expectedTotalBytes != null
                        ? loadingProgress.cumulativeBytesLoaded /
                            loadingProgress.expectedTotalBytes
                        : null,
                  ),
                );
              },
              errorBuilder: (_, error, s) {
                return SizedBox();
              },
            ),
            Positioned(
              height: 30,
              bottom: 0,
              left: 0,
              right: 0,
              child: Container(
                  color: Colors.black45,
                  child: Center(
                      child: Text(
                    '${snapshot.data.height}*${snapshot.data.width}',
                    style: TextStyle(color: Colors.white),
                  ))),
            )
          ],
        ),
      );
    }
    return Card(
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadiusDirectional.all(Radius.circular(16))),
      clipBehavior: Clip.antiAlias,
      child: widget, color: Colors.red,
      // margin: EdgeInsets.zero,
    );

    return OpenContainer(
      closedBuilder: (_, open) {
        return Card(
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadiusDirectional.all(Radius.circular(16))),
          clipBehavior: Clip.antiAlias,
          child: widget, color: Colors.red,
          // margin: EdgeInsets.zero,
        );
      },
      openBuilder: (_, close) {
        return Scaffold(
          body: Container(
              color: Colors.transparent,
              padding: EdgeInsets.all(100),
              child: Stack(
                children: [
                  Image.network(url),
                  Positioned(top: 0, left: 10, child: BackButton()),
                ],
              )),
        );
      },
    );
  }

  void _clipData() {
    // showDialog(
    //   context: context,
    //   child: Dialog(
    //     child: Image.network(url),
    //   )
    // );
  }
}
